﻿using System;
using System.ServiceProcess;
using Sustainalytics.Utils.Configuration;

namespace Sustainalytics.PregenerateScreeningReports.Service
{
    class Program
    {
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler((obj, exargs) =>
            {
                PSREventSource.Log.Exception((Exception)exargs.ExceptionObject);
                Console.WriteLine(((Exception)exargs.ExceptionObject).ToString());
                if (args.Length == 0)
                    TTLManager.Shutdown();
            });

            var registerClassMapHere =  new ScreeningToolReportDistributionSession();
            var id = System.Diagnostics.Process.GetCurrentProcess().Id;
            try
            {
               

                PSREventSource.Log.Enter(id, Environment.UserInteractive, args.Length);

                if (args.Length == 0)
                    TTLManager.Init(SettingsHelper.Read<string>("MachineName", "undefined"), 
                                    SettingsHelper.Read<bool>("ShutDownComputer", false),
                                    SettingsHelper.Read<string>("EmailFrom", "platformsupport@sustainalytics.com"),
                                    SettingsHelper.Read<string>("EmailTo", "platformsupport@sustainalytics.com"),
                                    SettingsHelper.Read<int>("ShutdownDelaySeconds", 3 * 60));
                

                if (Environment.UserInteractive)
                {
                    Console.WriteLine("Starting PregenerateScreeningReports");
                    if (args.Length == 0)
                    {
                        Console.WriteLine("Press any key to start ");
                        Console.ReadLine();
                    }
                    
                    var service = new PregenerateScreeningReports();
                    service.Start(args);

                    Console.WriteLine("press any key to exit ........");
                    Console.ReadLine();
                    service.Stop();
                }
                else
                {
                    if (args.Length == 0) // run as service
                        ServiceBase.Run(new PregenerateScreeningReports());
                    else
                    {
                        // run as sub process
                        var service = new PregenerateScreeningReports();
                        service.Start(args);
                    }
                }
            }
            catch(PSR_TTLExpired ex)
            {
                PSREventSource.Log.Exception(ex);
            }
            catch(Exception ex)
            {
                PSREventSource.Log.Exception(ex);
            }
            finally
            {
                PSREventSource.Log.Exit(id);
                if (args.Length == 0)
                    TTLManager.Shutdown();

            }
        }
    }
}
